package com.example.serviceconsumer.controller;

import com.example.serviceconsumer.model.Product;
import com.example.serviceconsumer.service.ProductResilienceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/resilience-test")
public class ResilienceTestController {

    @Autowired
    private ProductResilienceService productResilienceService;

    // 测试断路器A (失败率阈值30%)
    @GetMapping("/circuit-breaker-a")
    public ResponseEntity<List<Product>> testCircuitBreakerA() {
        System.out.println("测试断路器A: 失败率阈值30%, 时间窗口10秒, 最小请求5个");
        return productResilienceService.getAllProductsProtected();
    }

    // 测试断路器B (失败率50% + 慢调用30%)
    @GetMapping("/circuit-breaker-b/{id}")
    public ResponseEntity<Product> testCircuitBreakerB(@PathVariable Long id) {
        System.out.println("测试断路器B: 失败率阈值50%, 慢调用阈值30%(>2秒), 时间窗口10秒");
        return productResilienceService.getProductByIdProtected(id);
    }

    // 测试断路器B的慢调用场景
    @GetMapping("/circuit-breaker-b-slow")
    public ResponseEntity<Product> testCircuitBreakerBSlow() {
        System.out.println("测试断路器B慢调用: 访问ID=999 (3秒延迟)");
        return productResilienceService.getProductByIdProtected(999L);
    }

    // 测试断路器B的失败场景
    @GetMapping("/circuit-breaker-b-fail")
    public ResponseEntity<Product> testCircuitBreakerBFail() {
        System.out.println("测试断路器B失败: 访问ID=888 (异常)");
        return productResilienceService.getProductByIdProtected(888L);
    }

    // 批量测试断路器B的随机慢调用
    @GetMapping("/batch-test-b-slow/{count}")
    public String batchTestCircuitBreakerBSlow(@PathVariable int count) {
        System.out.println("批量测试断路器B慢调用: 发送" + count + "个请求到ID范围100-199");
        int successCount = 0;
        int slowCount = 0;
        int failureCount = 0;
        
        for (int i = 0; i < count; i++) {
            long id = 100L + (i % 100); // ID范围 100-199
            try {
                long startTime = System.currentTimeMillis();
                ResponseEntity<Product> response = productResilienceService.getProductByIdProtected(id);
                long duration = System.currentTimeMillis() - startTime;
                
                if (response.getStatusCode().is2xxSuccessful()) {
                    if (duration > 2000) {
                        slowCount++;
                    } else {
                        successCount++;
                    }
                } else {
                    failureCount++;
                }
            } catch (Exception e) {
                failureCount++;
            }
            
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        
        return String.format("断路器B慢调用测试完成: 成功%d次, 慢调用%d次, 失败%d次, 慢调用率%.2f%%", 
                successCount, slowCount, failureCount, (double)slowCount/(successCount+slowCount+failureCount)*100);
    }

    // 批量测试断路器B的随机失败
    @GetMapping("/batch-test-b-fail/{count}")
    public String batchTestCircuitBreakerBFail(@PathVariable int count) {
        System.out.println("批量测试断路器B失败: 发送" + count + "个请求到ID范围200-299");
        int successCount = 0;
        int failureCount = 0;
        
        for (int i = 0; i < count; i++) {
            long id = 200L + (i % 100); // ID范围 200-299
            try {
                ResponseEntity<Product> response = productResilienceService.getProductByIdProtected(id);
                if (response.getStatusCode().is2xxSuccessful()) {
                    successCount++;
                } else {
                    failureCount++;
                }
            } catch (Exception e) {
                failureCount++;
            }
            
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        
        return String.format("断路器B失败测试完成: 成功%d次, 失败%d次, 失败率%.2f%%", 
                successCount, failureCount, (double)failureCount/(successCount+failureCount)*100);
    }

    // --- 新增: 测试线程池隔离器的端点 ---
    @GetMapping("/bulkhead-threadpool")
    public CompletableFuture<String> testThreadPoolBulkhead() {
        System.out.println("接收隔离器测试请求，线程: " + Thread.currentThread().getName());
        return productResilienceService.testThreadPoolBulkhead();
    }

    // 测试限流器 (2秒内最多5个请求)
    @GetMapping("/rate-limiter/{id}")
    public ResponseEntity<Product> testRateLimiter(@PathVariable Long id) {
        System.out.println("测试限流器: 刷新周期2秒, 周期内最多5个请求");
        return productResilienceService.getProductByIdWithRateLimiter(id);
    }

    // 批量测试断路器A (用于快速触发失败率)
    @GetMapping("/batch-test-a/{count}")
    public String batchTestCircuitBreakerA(@PathVariable int count) {
        System.out.println("批量测试断路器A: 发送" + count + "个请求");
        int successCount = 0;
        int failureCount = 0;
        
        for (int i = 0; i < count; i++) {
            try {
                ResponseEntity<List<Product>> response = productResilienceService.getAllProductsProtected();
                if (response.getStatusCode().is2xxSuccessful()) {
                    successCount++;
                } else {
                    failureCount++;
                }
            } catch (Exception e) {
                failureCount++;
            }
            
            // 短暂延迟避免过快请求
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        
        return String.format("批量测试完成: 成功%d次, 失败%d次, 失败率%.2f%%", 
                successCount, failureCount, (double)failureCount/count*100);
    }

    // 批量测试限流器
    @GetMapping("/batch-test-rate-limiter/{count}")
    public String batchTestRateLimiter(@PathVariable int count) {
        System.out.println("批量测试限流器: 快速发送" + count + "个请求");
        int successCount = 0;
        int limitedCount = 0;
        
        for (int i = 0; i < count; i++) {
            try {
                ResponseEntity<Product> response = productResilienceService.getProductByIdWithRateLimiter(1L);
                if (response.getStatusCode().is2xxSuccessful()) {
                    successCount++;
                } else {
                    limitedCount++;
                }
            } catch (Exception e) {
                limitedCount++;
            }
        }
        
        return String.format("限流测试完成: 成功%d次, 被限流%d次", successCount, limitedCount);
    }
} 